/*
 * @Author: Jack Chao
 * @Date: 2025-05-05 14:45:24
 * @LastEditors: Jack Chao
 * @LastEditTime: 2025-05-09 12:45:00
 * @Description: 3D柱状图组件
 */
import React from 'react';
import { useEffect, useRef } from 'react';
// 恢复静态导入，确保组件能够正确加载
import 'echarts-gl'; // 引入3D扩展
import { ChartConfig, DataItem, DataConfig, ThemeOption } from '../../types/index';
import ChartBase, { ChartBaseRef } from './ChartBase/index'; // 更新导入路径
import { ChartType } from '../../types/chartTypes'; // 导入图表类型

interface Bar3DChartProps {
    data?: DataItem[];
    config?: ChartConfig;
    dataConfig?: DataConfig;
    theme?: ThemeOption;
    height?: number | string;
    width?: number | string;
    style?: React.CSSProperties;
    className?: string;
    onChartCreated?: (chart: any) => void;
    onChartClicked?: (params: any) => void;
}

const Bar3DChart: React.FC<Bar3DChartProps> = ({
    data,
    config: propConfig,
    dataConfig,
    theme,
    height = 400,
    width = '100%',
    style,
    className,
    onChartCreated,
    onChartClicked
}) => {
    const chartRef = useRef<ChartBaseRef>(null);
    // 创建一个工作副本，避免直接修改props
    const config: ChartConfig = { type: ChartType.BAR_3D, ...(propConfig || {}) };

    // 确保配置中包含3D图表所需的网格设置
    useEffect(() => {
        // 确保grid配置存在
        if (!config.grid) {
            config.grid = {
                show: true,
                boxWidth: 200,
                boxDepth: 80,
                boxHeight: 100
            };
        } else {
            // 创建一个新的grid对象以避免直接修改原始对象属性
            config.grid = {
                ...config.grid,
                // 使用空值合并运算符确保3D特有属性存在
                boxWidth: config.grid.boxWidth ?? 200,
                boxDepth: config.grid.boxDepth ?? 80,
                boxHeight: config.grid.boxHeight ?? 100
            };
        }

        // 确保图表类型正确
        if (!config.type || config.type !== ChartType.BAR_3D) {
            config.type = ChartType.BAR_3D;
        }

        // 确保series配置正确
        if (config.series && Array.isArray(config.series)) {
            config.series = config.series.map(series => ({
                ...series,
                // 确保使用正确的类型名称
                type: ChartType.BAR_3D
            }));
        } else {
            // 如果没有series配置，添加默认配置
            config.series = [{
                type: ChartType.BAR_3D,
                data: [[0, 0, 10], [1, 0, 20], [0, 1, 15]]
            }];
        }
    }, [config, propConfig]);

    return (
        <ChartBase
            ref={chartRef}
            data={data}
            option={config}
            dataConfig={dataConfig}
            theme={theme}
            height={height}
            width={width}
            style={style}
            className={className}
            onChartReady={onChartCreated}
            onEvents={onChartClicked ? { click: onChartClicked } : undefined}
        />
    );
};

export default Bar3DChart;